package com.ujoku.scheduled;

import com.labillusion.core.util.StopWatch;
import com.ujoku.domain.Order;
import com.ujoku.domain.OrderStatus;
import com.ujoku.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Greg.Chen on 2015/2/11.
 */
@Service
public class OrderTask {
    private static Logger logger = LoggerFactory.getLogger(OrderTask.class);

    @Autowired
    private OrderService orderService;

    @Scheduled(initialDelay = 5000,fixedRate=300000)
    public void cancelOrder(){
        StopWatch stopWatch = new StopWatch();

        Map<String,Object> query = new HashMap<>();
        query.put("legacyOrder", true);
        query.put("status", OrderStatus.Created);
        List<Order> orderList = orderService.selectList(query);
        if(orderList.size() == 0)
            return;

        for(Order order : orderList){
            orderService.rollBackGoodsSaleCount(order);
            orderService.rollBackMyListItemSaleCount(order);

            order.setStatus(OrderStatus.Cancel);
            orderService.update(order);
        }

        logger.debug("cancel order task, elapsed = " + stopWatch.elapsedTime() + "ms");

    }


}
